<template>
  <div class="playsong">
    <Myalert :message="msg" :color="alertColor" v-if="isAlertShow" @close-alert="closeAlertFn"></Myalert>
    <!-- 背景 -->
    <div class="bg">
      <img v-if="picUrl" :src="picUrl" alt="" />
    </div>

    <div class="layout">
      <div class="back">
        <img src="../assets/返回.png" @click="back" alt="">
        <img v-if="!likeObject.ishaveLike && id && isHaveAudio" @click="addLikeMusic(id)" src="../assets/收藏 (3).png"
          alt="">
        <img v-else-if="likeObject.ishaveLike && id && isHaveAudio" src="../assets/收藏 (2).png" alt=""
          @click="addLikeMusic(id)">

      </div>
      <div class="wrapper" v-if="id">
        <audio controls autoplay :src="`https://music.163.com/song/media/outer/url?id=${id}.mp3`" ref="audio"
          @error="handleAudioError" @timeupdate="timeupdateFn" @end="endFn" @canplay="canplayFn"></audio>
      </div>

      <p class="songname">{{ songname }}</p>
      <!-- 歌词 -->
      <div class="audio-lyric" @click="isFeng = !isFeng" v-if="isHaveAudio && !isFeng">
        <ul v-if="id" :style="`transform:translateY(-${num * height}px)`">
          <li v-for="(item, index) in lyrics" :class="index == num ? 'active' : ''">
            {{ item.text }}
          </li>
        </ul>
        <span v-if="!id">抱歉,暂无歌曲信息~~</span>
      </div>
      <span v-if="!isHaveAudio && !isFeng" class="noAudio">抱歉,暂无本歌曲的音频文件~~</span>

      <!-- 封面 -->
      <div v-if="isFeng" class="play-cover" @click="isFeng = !isFeng">
        <ul :class="['ani-rotate', isPlay == true ? '' : 'ani-rotate-pause']">
          <li>
            <div>
              <img v-if="picUrl" :src='picUrl' alt="" />
            </div>
          </li>
        </ul>
      </div>

      <!-- 进度条 -->
      <div class="play-progress">
        <div class="left">{{ curTime | formatime }}</div>
        <div class="center">
          <input type="range" v-model="v1" value="0" min="0" max="100" />
        </div>
        <div class="right">{{ durTime | formatime }}</div>
      </div>

      <!-- 按钮 -->
      <div class="btn" v-if="(id && isHaveAudio) || (id && isFeng)">
        <!-- <button @click="playFn">播放</button>
      <button @click="pauseFn">暂停</button> -->
        <img src="../assets/bg-previous.png" alt="" @click="pre">
        <img v-if="!isPlay" @click="playFn" src="../assets/播放.png" alt="">
        <img v-if="isPlay" @click="pauseFn" src="../assets/暂停.png" alt="">
        <img src="../assets/bg-next.png" alt="" @click="next">
      </div>

      <!-- 提醒上下 -->
      <span v-if="!ispreornext" class="tip">当前歌曲没有上一首或者下一首</span>
    </div>
  </div>
</template>

<script>
import Myalert from '@/components/Myalert.vue';
export default {
  components: {
    Myalert
  },
  name: 'SongPlay',
  data() {
    return {
      isJilu: false,
      ishaveLike: false,
      msg: "这是xxx弹窗",
      isAlertShow: false,
      alertColor: '#fff',
      likeMusic: [],
      durTime: 0,
      songname: '',
      ispreornext: true,
      id: '',
      picUrl: "",
      isPlay: true,
      lyrics: [],
      num: 0,
      height: 50,
      curTime: 0,
      isLike: false,
      isPre: false,
      isNext: false,
      isShowLike: true,
      isHaveAudio: true,
      isFeng: false,
      pNewsongs: [],
      likeArr: [],
      hotArr: [],
      type: '',
      nowArr: [],
      idArr: [],
      changeId: 0,
      picArr: [],
      nameArr: [],
      v1: 0, // 记录进度
      musics: [],
      likes: [],
      likeObject: { id: '', ishaveLike: '' },
      nowIndex: 0,
    }
  },
  // 过滤器
  filters: {
    // 格式化时间
    formatime(value) {
      let h = 0,
        m = 0,
        s = 0;
      h = Math.floor(value / 3600);
      m = Math.floor((value % 3600) / 60);
      s = Math.floor(value % 60);
      h = h < 10 ? "0" + h : h;
      m = m < 10 ? "0" + m : m;
      s = s < 10 ? "0" + s : s;
      return `${h}:${m}:${s}`;
    },
  },
  // 侦听器
  watch: {
    $route: {
      immediate: true,
      deep: true,
      handler(route) {
        let id = route.query.id;
        let picUrl = route.query.picUrl;
        if (id) {
          this.id = id;
          let newArr = this.musics.filter((item) => item.song.id == id);

          // console.log(newArr)
          if (newArr.length == 1) {
            this.picUrl = newArr[0].picUrl;
            this.name = newArr[0].name;
          }
          this.getSongLyricFn(id)
        }
        if (picUrl) {
          this.picUrl = picUrl;
        }
      }
    },
    // id(nValue){
    //     // 观察id的变化
    //     this.isLikeMusicFn(nValue);
    // },
    // 观察播放时长的变化
    curTime: {
      handler(nValue, oValue) {
        // console.log({ nValue, oValue });
        // let num ;
        if(
          this.lyrics.length!=0
        ){
          for (let i = 0; i < this.lyrics.length - 1; i++) {
            // 判断当前这一行歌词索引值所在区间
            if (this.lyrics[i].times && this.lyrics[i + 1].times) {
              if (
                nValue >= this.lyrics[i].times &&
                nValue <= this.lyrics[i + 1].times
              ) {
                this.num = i;
                break;
              }
            }
          }
          // console.log("索引值:", this.num);
          if (this.lyrics[this.lyrics.length - 1].times) {
            if (nValue >= this.lyrics[this.lyrics.length - 1].times) {
              nValue = this.lyrics.length - 1;
            }
          }
        }
      },
    },
    //观察歌词id的变化
    changeId: {
      immediate: true,
      deep: true,
      handler(nValue, oValue) {
        // console.log({ nValue, oValue });
        this.id = nValue
        this.getSongLyricFn(this.id)

      },
    }

  },
  created() {
    //  获取url参数
    let query = this.$route.query;
    // console.log(query);
    this.id = query.id
    this.getSongLyricFn(this.id)
    // console.log(this.id);
    this.type = query.type
    // console.log(query.songname);
    this.songname = query.songname

    this.pNewsongs = JSON.parse(localStorage.getItem('pNewsongs'))
    this.likeArr = JSON.parse(localStorage.getItem('likeArr'))
    this.hotArr = JSON.parse(localStorage.getItem('hotArr'))

    if (this.type == 'tuijian') {
      this.nowArr = this.pNewsongs
      this.nowArr.forEach(element => {
        this.idArr.push(element.song.id)
        this.picArr.push(element.picUrl)
        this.nameArr.push(element.name)
      });
    }
    if (this.type == 'mylike') {
      this.nowArr = this.likeArr
      this.nowArr.forEach(element => {
        this.idArr.push(element.id)
        this.nameArr.push(element.name)
        this.picArr = []
      });
    }
    if (this.type == 'hotTop') {
      this.nowArr = this.hotArr
      this.nowArr = []
      this.picArr = []
      this.nowArr.forEach(element => {
        this.nameArr.push(element.name)
      });
    }
    // console.log(this.nowArr);
    // console.log(this.idArr);
    // console.log(this.picArr);
    // console.log(this.nameArr);
    // console.log(this.id);
    // 获取本地存储的歌曲
    let musicsstr = localStorage.getItem("MUSICS");
    if (musicsstr) {
      //  console.log('--->',musicsstr)
      this.musics = JSON.parse(musicsstr);
      //  console.log('--->',this.musics)
      let newArr = this.musics.filter((item) => item.song.id == this.id);
      // console.log(newArr);
      if (newArr.length == 1) {
        this.picUrl = newArr[0].picUrl;
        this.name = newArr[0].name;
      }

      // 循环数组
      for (let i = 0; i < this.musics.length; i++) {
        if (this.musics[i].song.id == query.id) {
          // 获取当前歌曲所在的索引值
          this.index = i;
          break;
        }
      }
    }
    // 初始化时长
    this.curTime = 0;
    this.durTime = 0;

    // // 判断路由是否存在id
    // if(query.id != undefined) {
    //    this.isLikeMusicFn(query.id);
    // }


    // 从本地检查是否存在收藏音乐列表
    let likesArr = JSON.parse(localStorage.getItem("LIKES")) || []; // 如果LIKES不存在，则默认为空数组  
    // [{id:xxx,ishaveLike:false}]
    this.likes = likesArr
    if (likesArr) {
      likesArr.forEach((item, index) => {
        if (item.id == this.id) {
          this.likeObject.id = this.id
          this.likeObject.ishaveLike = true
        }
      })
    } else {
      this.likeObject.id = this.id
      this.likeObject.ishaveLike = false
    }

  },

  // 设置方法
  methods: {
    // 关闭自定义弹窗
    closeAlertFn(value) {
      // 检查代码
      // console.log(value)
      this.isAlertShow = value;
    },
    // 显示自定义弹窗
    showAlertFn(message, color = "#000") {
      this.msg = message;
      this.isAlertShow = true;
      this.alertColor = color;
    },
    handleAudioError() {
      // console.error('音频文件加载失败');  
      this.isHaveAudio = false
    },
    //前一首
    pre() {
      this.isPre = true
      if (this.idArr.length != 0) {
        // console.log(this.idArr);
        // console.log(this.id);
        let index = this.idArr.indexOf(+this.id)
        // console.log(index);
        if (index == 0) {
          this.ispreornext = false
          this.id = this.idArr[0]
          this.picUrl = this.picArr[0]
          this.songname = this.nameArr[0]
        } else {
          this.ispreornext = true
          this.id = this.idArr[index - 1]
          this.picUrl = this.picArr[index - 1]
          this.songname = this.nameArr[index - 1]
        }
        this.getSongLyricFn(this.id)
      } else {
        // console.log('没有上一首或者下一首');
        this.ispreornext = false
      }
    },
    // 后一首
    next() {
      this.isNext = true
      if (this.idArr.length != 0) {
        // console.log(this.idArr);
        // console.log(this.id);
        let index = this.idArr.indexOf(+this.id)
        // console.log(index);
        if (index == this.idArr.length - 1) {
          this.ispreornext = false
          this.id = this.idArr[this.idArr.length - 1]
          this.picUrl = this.picArr[this.picArr.length - 1]
          this.songname = this.nameArr[this.nameArr.length - 1]
        } else {
          this.ispreornext = true
          this.id = this.idArr[index + 1]
          this.picUrl = this.picArr[index + 1]
          this.songname = this.nameArr[index + 1]
        }
        // console.log(this.id);
        this.getSongLyricFn(this.id)
      } else {
        // console.log('没有上一首或者下一首');
        this.ispreornext = false
      }
    },

    // 添加收藏音乐
    addLikeMusic(id) {
  // 获取用户身份
  let user_id = localStorage.getItem("USER_ID");
  if (user_id == undefined) {
    this.showAlertFn("您还没有登录哦~~", '#fb0201');
    return false;
  }

  // 从本地检查是否存在收藏音乐列表
  let likesArr = JSON.parse(localStorage.getItem("LIKES")) || [];
  this.likes = likesArr;
  console.log(this.likes);

  // 判断当前歌曲是否已经收藏
  let isLiked = false;
  let index = -1;

  for (let i = 0; i < this.likes.length; i++) {
    if (this.likes[i].id == id) {
      isLiked = true;
      index = i;
      break;
    }
  }

  // 如果当前歌曲已收藏，则从收藏列表中移除
  if (isLiked) {
    this.likes.splice(index, 1);
    this.likeObject = { id: id, ishaveLike: false };
  } else {
    // 如果当前歌曲未收藏，则将其添加到收藏列表中
    this.likes.push({ id: id, ishaveLike: true });
    this.likeObject = { id: id, ishaveLike: true };
  }

  // 更新localStorage  
  localStorage.setItem("LIKES", JSON.stringify(this.likes));
  console.log(this.likeObject.ishaveLike);
}

    ,
    back() {
      this.$router.go(-1)
    },
    timeupdateFn() {
      let audio = this.$refs['audio'];
      if (audio) {
        this.curTime = audio.currentTime;
        // 计算进度条
        this.v1 = (this.curTime / this.durTime) * 100;
      }
    },
    endFn() {
      this.next()
    },
    playFn() {
      // 获取audio标签
      let audio = this.$refs['audio'];
      if (audio) {
        audio.play();
        this.isPlay = true
      }
    },
    pauseFn() {
      // 获取audio标签
      let audio = this.$refs['audio'];
      if (audio) {
        audio.pause();
        this.isPlay = false
      }
    },
    canplayFn() {
      let audio = this.$refs["audio"];
      if (audio) {
        // 获取总时长
        this.durTime = audio.duration;
      }
    },
    async getSongLyricFn(id) {
      try {
        if (id) {
          const response = await this.$axios.get(`https://apis.netstart.cn/music/lyric?id=${id}`);
          // console.log(response.data);
          let rep = /\[(\d{2}):(\d{2}).(\d{2,})\](.{0,})/;
          let newArr = response.data.lrc.lyric.split('\n')
          // console.log(response.data.lrc.lyric.split('\n'));
          if (newArr[newArr.length - 1].length == 0) {
            newArr.pop()
          }
          this.lyrics = []
          newArr.map((item, index) => {
            if (rep.test(item)) {
              let info = rep.exec(item);
              let [, minutes, seconds, millseconds, text] = info;
              // console.log({minutes, seconds, millseconds,text});//
              let obj = {};
              obj.times = ((minutes - 0) * 60) + (seconds - 0) + (millseconds - 0) / 1000;
              obj.text = text;
              obj.id = index;
              // 把每一行歌词信息添加到数组中
              this.lyrics.push(obj);
              return this.lyrics;
            }
          })
        }
        // console.log(this.lyrics);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    },
  },
}
</script>

<style lang="less" scoped>
@import "../style/variable.less";

// 定义动画
@keyframes loop {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

// 进度条
.play-progress {
  color: #fff;
  font-size: 16px;
  width: 100%;
  position: fixed;
  bottom: 20px;
  left: 0;
  display: flex;
  padding: 0 15px;
  box-sizing: border-box;
  height: 100px;
  align-items: center;

  .left,
  .right {
    width: 80px;
    text-align: center;
  }

  .center {
    flex-basis: calc(100% - 160px);

    input {
      width: 100%;
      height: 5px;
      vertical-align: middle;
      margin-top: -2px;
      background-color: #a68fec;
    }
  }
}

.songname {
  width: 100%;
  color: #fff;
  position: absolute;
  top: 80px;
  font-size: 30px;
  text-align: center;
  z-index: 9999999999999999999;
}

.tip {
  display: inline-block;
  width: 100%;
  text-align: center;
  color: #fff;
}

.ani-rotate {
  animation: loop 5s infinite linear;
}

.ani-rotate-pause {
  animation-play-state: paused;
}

// 根节点
.play {
  position: fixed;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: 1000000;
  top: 0;
  left: 0;
}

.layout {
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: 1000000;
  top: 0;
  left: 0;
}

.bg {
  position: fixed;
  width: 100%;
  height: 100%;
  filter: blur(100px);
  backdrop-filter: blur(100px);
  top: 0;
  left: 0;
  z-index: 1;

  img {
    width: 100%;
    height: 100%;
  }
}

// 封面
.play-cover {
  width: 100%;
  margin: 150px auto;
  display: flex;
  justify-content: center;
  box-sizing: border-box;

  ul {
    width: 200px;
    height: 200px;
    border: 20px solid #241e1b;
    box-sizing: border-box;
    border-radius: 50%;

    li {
      width: 166px;
      height: 166px;
      border: 40px solid #3e3e3e;
      box-sizing: border-box;
      display: block;
      border-radius: 50%;
      margin-left: -2px;
      margin-top: -2px;

      div {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;

        // overflow: hidden;
        img {
          vertical-align: middle;
          width: 110%;
          border-radius: 50%;
        }
      }
    }
  }
}

.noAudio {
  position: absolute;
  margin-top: 200px;
  text-align: center;
  width: 100%;
  color: #fff;
}

.playsong {
  position: fixed;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-repeat: no-repeat;
  z-index: 1000000;
  background-color: #a68fec;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  font-family: "logotext";
  overflow: hidden;
  position: relative;
}

.back {
  position: relative;

  img {
    width: 40px;
    height: 40px;
    position: absolute;

    &:nth-child(1) {
      left: 10px;
      top: 20px;
    }

    &:nth-child(2) {
      right: 20px;
      top: 20px;
    }

    &:nth-child(3) {
      right: 20px;
      top: 20px;
    }
  }
}

.wrapper {
  height: 0;
  overflow: hidden;
}

.audio-lyric {
  width: 80%;
  height: 45%;
  font-size: 18px;
  text-align: center;
  overflow: hidden;
  margin: 0 auto;
  margin-top: 150px;

  span {
    font-size: 22px;
    color: #fff;
  }

  ul {
    width: 100%;
    transform: translateY(0px);
    transition: transform 500ms;

    li {
      height: 50px;
      line-height: 50px;
      transition: all .2s;
      overflow: hidden;
      /* 防止文本换行 */
      white-space: nowrap;
      /* 当文本溢出时显示省略号 */
      text-overflow: ellipsis;
      color: #fff;

      &.active {
        color: #7b5dd6;
        font-size: 26px;
        font-weight: bolder;
      }
    }
  }
}

.btn {
  width: 50px;
  height: 50px;
  margin: 50px auto;
  display: flex;
  width: 300px;
  justify-content: space-around;

  img {
    width: 40px;
    height: 40px;
    background-size: cover;

    &:nth-child(2) {
      width: 50px;
      height: 50px;
      margin-top: -5px;
    }
  }
}
</style>